using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace OllieExplorer
{
    public struct Selection
    {
        public int? Row;
        public string Key;
    }

    public partial class GridControl : UserControl
    {
        const int WM_KEYDOWN = 0x100;
        const int WM_SYSKEYDOWN = 0x104;

        public GridControl()
        {
            _Columns.ColumnAdded += ColumnAdded;
            _Columns.ColumnRemoved += ColumnRemoved;
            _Columns.ColumnCleared += ColumnsCleared;
            _Columns.ColumnChanged += ColumnAdded;
            InitializeComponent();
        }

        private readonly GridColumns _Columns = new GridColumns();
        private int _ScrollX;
        private int _ScrollY;
        private int _MaxColumnHeadHeight;
        private int _MaxColumnRowHeight;
        private int _MaxScrollX;
        private Selection _Selected = new Selection();
        private int _CursorY = 0;
        private int _OffsetY = 0;
        private int _ViewWindow = 100;
        private GridColumn _ColumnOver;
        private int _StartResize;
                
        public delegate void LoadNewDataDelegate(GridControl sender, int startRow);

        private LoadNewDataDelegate _LoadNewData;
        private LoadNewDataDelegate _LoadNewTopData;
        


        internal LoadNewDataDelegate LoadNewData
        {
            get
            {
                return _LoadNewData;
            }
            set
            {
                _LoadNewData = value;
            }
        }

        internal LoadNewDataDelegate LoadNewTopData
        {
            get
            {
                return _LoadNewTopData;
            }
            set
            {
                _LoadNewTopData = value;
            }
        }

        public GridColumns Columns
        {
            get
            {
                return _Columns;
            }
        }

        public int ViewWindow
        {
            get
            {
                return _ViewWindow;
            }
            set
            {
                _ViewWindow = value;
            }
        }
        
        public int OffsetY
        {
            get
            {
                return _OffsetY;
            }
        }

        public int ScrollY
        {
            get
            {
                return _ScrollY;
            }
            set
            {
                _ScrollY = value;
            }
        }

        public int ScrollX
        {
            get
            {
                return _ScrollX;
            }
            set
            {
                _ScrollX = value;
            }
        }

        public int MaxScrollX
        {
            get
            {
                return _MaxScrollX;
            }
        }

        public int MaxScrollY
        {
            get
            {
                var preMaxScrollY = _Columns.Count - (Height - _MaxColumnHeadHeight)/_MaxColumnRowHeight;
                return preMaxScrollY < 0 ? 0 : preMaxScrollY;
            }
        }

        public void Clear()
        {
            foreach(GridColumn gridColumn in _Columns)
            {
                gridColumn.Data.Clear();
                gridColumn.MakeDirty();
            }

        }

        private void RecalculateColumnHeights()
        {
            _MaxColumnHeadHeight = 0;
            _MaxColumnRowHeight = 0;
            foreach (GridColumn column in _Columns)
            {
                if(_MaxColumnHeadHeight < column.Font.Height)
                {
                    _MaxColumnHeadHeight = column.Font.Height; 
                }

                if (_MaxColumnRowHeight < column.Font.Height)
                {
                    _MaxColumnRowHeight = column.Font.Height;
                }
            }
        }

        private void GridControlOnPaint(object sender, PaintEventArgs e)
        {
            foreach (GridColumn column in _Columns)
            {
                if (column.End < _ScrollX && column.Start > _ScrollX + Width)
                {
                    continue;
                }
                var x = column.Start - _ScrollX;
                var graphicsContainer =e.Graphics.BeginContainer();
                e.Graphics.SetClip(new Rectangle(x, 0, column.Width, Height));
                column.Draw(e.Graphics, x, _MaxColumnHeadHeight, _MaxColumnRowHeight, _ScrollY, true);
                e.Graphics.EndContainer(graphicsContainer);
            }
            
            e.Graphics.Flush();
        }

        public Dictionary<string, string> GetRow(int row)
        {
            var dataRow = new Dictionary<string, string>();
            foreach(GridColumn column in _Columns)
            {
                dataRow.Add(column.ColumnHeadding, column.Data[row]);
            }
            return dataRow;
        }

        public int AddRow(Dictionary<string, string> dataRow)
        {
            foreach (GridColumn column in _Columns)
            {
                column.Data.Add(dataRow[column.ColumnHeadding]);
                column.MakeDirty();
            }
            return _Columns.Count == 0 ? 0 : _Columns[0].Data.Count;
        }

        public int AddRow(DataRow dataRow)
        {
            foreach (GridColumn column in _Columns)
            {                
                column.Data.Add(Convert.ToString(dataRow[column.ColumnHeadding]));
                column.MakeDirty();
            }
            return _Columns.Count == 0 ? 0 : _Columns[0].Data.Count;
        }
        public GridColumn FindColumn(string name)
        {
            // TODO: Create a hash table lookup to speed this up a bit / lot!!
            foreach(GridColumn column in _Columns)
            {
                if(column.ColumnHeadding ==  name)
                {
                    return column;
                }
            }
            return null;
        }

        public int AddTopRows(DataTable dataTable)
        {
            if (dataTable.Rows.Count > 0)
            {
                var columnLookup = new List<GridColumn>();
                var counter = 0;
                foreach (DataColumn dataColumn in dataTable.Columns)
                {
                    var column = FindColumn(dataColumn.ColumnName);
                    columnLookup.Add(column);
                    counter++;
                }

                var columnCount = counter;
                foreach (DataRow dataRow in dataTable.Rows)
                {
                    for (counter = 0; counter < columnCount; counter++)
                    {
                        if (columnLookup[counter] != null)
                        {
                            columnLookup[counter].Data.Insert(0, Convert.ToString(dataRow[counter]));
                        }
                    }
                }

                foreach (GridColumn column in _Columns)
                {
                    column.MakeDirty();
                }
                _ScrollY += dataTable.Rows.Count;
                _OffsetY -= dataTable.Rows.Count;
            }

            return _Columns.Count == 0 ? 0 : _Columns[0].Data.Count;
        }

        public int AddRows(DataTable dataTable)
        {
            if (dataTable.Rows.Count > 0)
            {
                var columnLookup = new List<GridColumn>();
                var counter = 0;
                foreach (DataColumn dataColumn in dataTable.Columns)
                {
                    var column = FindColumn(dataColumn.ColumnName);
                    columnLookup.Add(column);
                    counter++;
                }

                var columnCount = counter;
                foreach (DataRow dataRow in dataTable.Rows)
                {
                    for (counter = 0; counter < columnCount; counter++)
                    {
                        if (columnLookup[counter] != null)
                        {
                            columnLookup[counter].Data.Add(Convert.ToString(dataRow[counter]));
                        }
                    }
                }

                foreach (GridColumn column in _Columns)
                {
                    column.MakeDirty();
                }
            }
            return _Columns.Count == 0 ? 0 : _Columns[0].Data.Count;
        }

        public void UpdateRow(int row, Dictionary<string, string> dataRow)
        {
            foreach (GridColumn column in _Columns)
            {
                column.Data[row] = dataRow[column.ColumnHeadding];
                column.MakeDirty();
            }
            
        }

        public void DeleteRow(int row)
        {
            foreach (GridColumn column in _Columns)
            {
                column.Data.RemoveAt(row);
            }
        }

        public int RowCount
        {
            get { return _Columns.Count == 0 ? 0 : _Columns[0].Data.Count; }
        }

        private void ColumnDataDirty(GridColumn gridColumn)
        {
            RecalculateColumnHeights();
            Invalidate();
        }

        private void ColumnRezied(GridColumn gridColumn)
        {
            _MaxScrollX = _Columns[_Columns.Count - 1].End - Width;
            Invalidate();
        }

        private void GridControlOnMouseDown(object Sender, MouseEventArgs eventArgs)
        {

            System.Diagnostics.Debug.WriteLine(Focused);
            Select();
            Focus();
            System.Diagnostics.Debug.WriteLine(Focused);
            var foundColumn = FindColumn(eventArgs.X);
           
            if (foundColumn != null && foundColumn.MouseMovedDown != null)
            {

                var columnMouseEventArgs = new MouseEventArgs(eventArgs.Button, eventArgs.Clicks,
                                                                         eventArgs.X - (foundColumn.Start + _ScrollX),
                                                                         eventArgs.Y, eventArgs.Delta);
                foundColumn.MouseMovedDown(foundColumn, columnMouseEventArgs);
            }

            if ((eventArgs.Button & MouseButtons.Left) != MouseButtons.Left)
            {
                return;
            }
            if(Cursor == Cursors.VSplit)
            {
                _StartResize = eventArgs.X;
            }
        }

        private void GridControlOnMouseUp(object Sender, MouseEventArgs eventArgs)
        {

            GridColumn foundColumn = FindColumn(eventArgs.X);
            
            if (foundColumn != null && foundColumn.MouseMovedUp != null)
            {

                var columnMouseEventArgs = new MouseEventArgs(eventArgs.Button, eventArgs.Clicks,
                                                                         eventArgs.X - (foundColumn.Start + _ScrollX),
                                                                         eventArgs.Y, eventArgs.Delta);
                // TODO: Maybe do an OnMouseUp thing?
                foundColumn.MouseMovedUp(foundColumn, columnMouseEventArgs);
            }

            if ((eventArgs.Button & MouseButtons.Left) != MouseButtons.Left)
            {
                return;
            }
            if (Cursor != Cursors.VSplit)
            {
                return;
            }
            _ColumnOver.Width += eventArgs.X - _StartResize;
            Cursor = Cursors.Default;
        }

        private void GridControlOnMouseMove(object Sender, MouseEventArgs eventArgs)
        {
            if ((eventArgs.Button & MouseButtons.Left) != MouseButtons.None)
            {
                return;
            }
            Cursor = Cursors.Default;
            GridColumn foundColumn = FindColumn(eventArgs.X);
            if (foundColumn == null)
            {
                return;
            }

            if (eventArgs.X > (foundColumn.End - _ScrollX) - 1)
            {
                Cursor = Cursors.VSplit;
                _ColumnOver = foundColumn;
            }

            if (foundColumn.MouseMoved == null)
            {
                return;
            }

            var columnMouseEventArgs = new MouseEventArgs(eventArgs.Button, eventArgs.Clicks,
                                                                     eventArgs.X - (foundColumn.Start + _ScrollX),
                                                                     eventArgs.Y, eventArgs.Delta);
            foundColumn.MouseMoved(foundColumn, columnMouseEventArgs);

        }

        private GridColumn FindColumn(int x)
        {
            return _Columns.FindColumn(x + _ScrollX);
        }

        private void ColumnAdded(GridColumns gridColumns, int index)
        {
            gridColumns[index].DataDirty += ColumnDataDirty;
            gridColumns[index].Resized += ColumnRezied;
            RecalculateColumnHeights();
            // FIXME: Check for visibility bounds etc....
            Invalidate();
        }

        private void ColumnRemoved(GridColumns gridColumns, int index)
        {
            // FIXME: Check for visibility bounds etc....
            RecalculateColumnHeights();
            Invalidate();
        }

        private void ColumnsCleared(GridColumns gridColumns)
        {
            RecalculateColumnHeights();
            Invalidate();
        }

        private void RemoveTopRows()
        {
            var rowsToDelete = _ScrollY -  (_ViewWindow + 1);
            _OffsetY += rowsToDelete;
            _ScrollY -= rowsToDelete;
            foreach(GridColumn gridColumn in _Columns)
            {
                for(var counter = 0; counter < rowsToDelete; counter++)
                {
                    gridColumn.Data.RemoveAt(0);
                }
            }
        }

        private void RemoveBottomRows()
        {
            var rowsToDelete = RowCount - (_ScrollY + (Math.Floor(((decimal) Height - _MaxColumnHeadHeight)/_MaxColumnRowHeight)  + _ViewWindow));            
            foreach (GridColumn gridColumn in _Columns)
            {
                for (var counter = 0; counter < rowsToDelete; counter++)
                {
                    gridColumn.Data.RemoveAt(gridColumn.Data.Count - 1);
                }
            }

        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {

            if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
            {
                switch (keyData)
                {
                    case Keys.Down:
                        

                        if(_CursorY > RowCount + _OffsetY - _ViewWindow)
                        {
                            if(_LoadNewData != null)
                            {
                                _LoadNewData(this, _OffsetY + RowCount + 1);
                            }
                        }

                        if (_CursorY < RowCount + _OffsetY - 1)
                        {
                            _CursorY++;
                        }

                        if (_CursorY - _ScrollY >
                            Math.Floor(((decimal) Height - _MaxColumnHeadHeight)/_MaxColumnRowHeight) - 1)
                        {
                            _ScrollY++;
                        }

                        if (_ScrollY > _ViewWindow * 2)
                        {
                            RemoveTopRows();
                        }

                        Invalidate();
                        break;

                    case Keys.Up:
                        if (_CursorY > 0)
                        {
                            _CursorY--;
                        }
                        if (_CursorY - (_ScrollY + _OffsetY)< 0)
                        {
                            _ScrollY--;
                            if (_ScrollY < _ViewWindow)
                            {
                                if (_LoadNewTopData != null)
                                {
                                    _LoadNewTopData(this, _OffsetY - _ViewWindow);
                                }
                            }
                            if (_ScrollY + _ViewWindow * 2 < RowCount) // TODO: Possibly take into account the number of visible rows
                            {
                                RemoveBottomRows();
                            }
                        }
                        
                        Invalidate();
                        break;

                    case Keys.Tab:
                        //this->Parent->Text = S"TAB key captured";
                        break;
                }

            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void GridControl_KeyDown(object sender, KeyEventArgs e)
        {
         

            
            //System.Diagnostics.Debug.WriteLine(e.KeyValue);
        }

        private void GridControl_KeyPress(object sender, KeyPressEventArgs e)
        {
            
        }

        private void GridControl_KeyUp(object sender, KeyEventArgs e)
        {

        }

        public void Reset()
        {
            _OffsetY = 0;
            _ScrollY = 0;
            _CursorY = 0;
            _Selected.Row = null;
            _Selected.Key = null;
            Clear();
        }


           
    }
}
